package com.leyou.order.interceptor;

import com.leyou.common.auth.domain.UserHolder;
import com.leyou.common.constant.LyConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class UserInterceptor implements HandlerInterceptor {
    //会在处理器执行之前执行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String userIdStr = request.getHeader(LyConstants.USER_ID_KEY);
        if(StringUtils.isBlank(userIdStr)){
            log.info("【拦截器获取用户id】失败！当前用户未登录！");
        }
        //将当前用户的id存入到UserHolder中
        UserHolder.setId(Long.valueOf(userIdStr));
        return true;
    }

    //会在当次请求，当前线程彻底执行完后，执行，这里我们要移除掉当次线程上的用户id
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                 @Nullable Exception ex) throws Exception {
        UserHolder.remove();
    }
}
